package l2ft.gameserver.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Deprecated
public class MySqlConnection
{
	private static final Logger _log = LoggerFactory.getLogger(MySqlConnection.class);
	
	private String _query;
	private List<Object> _values = new ArrayList<>();//TODO
	private int valuesTableCount = 0;
	
	public MySqlConnection(String query, Object... values)
	{
		_query = query;
		for(Object value : values)
			_values.add(value);
	}
	
	//INSERT, dodanie do VALUES (x,x,x,x)
	//UPDATE, zamiana ? na value
	public void addValue(Object value)
	{
		_values.add(value);
	}
	
	/**
	 * Converting addedValues into syntax like: (21, 5, 'f', '2131')
	 */
	public void finishValues()
	{
		//From single values, making ", (21, 5, 'f', '2131')"
		String toQuery = (valuesTableCount > 0 ? ", " : "") + "(";
		for(Object value : _values)
		{
			if(value instanceof Number)
				toQuery += value+",";
			else if(value instanceof String)
				toQuery += "'"+value+"',";
			else
				System.out.println("!!!!!!!!!!!!!!!!!!!!! MySqlConnection error value:"+value);
		}
		_values.clear();
		valuesTableCount++;
		
		_query += toQuery.substring(0, toQuery.length()-1)+")";
	}
	
	
	public void execute()
	{
		System.out.println("making query:"+_query);
		
		finishQuery();
		
		System.out.println("made query:"+_query);
		try(Connection con = DatabaseFactory.getConnection();
				PreparedStatement statement = con.prepareStatement(_query))
		{
			statement.executeQuery();
		}
		catch(SQLException e)
		{
			_log.error("MySqlConnection: Error in query: "+_query, e);
		}
	}
	
	private void finishQuery()
	{
		for(Object value : _values)
		{
			_query = _query.replaceFirst("=\\?", "="+value);
		}
	}
}
